package com.example.saiaadmin.hander;

import com.example.saiaadmin.utils.ResultData;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * security 没有权限,被拒绝访问时的调用类
 *
 */
@Component
public class MissingRestAccessDeniedHandler implements AccessDeniedHandler {
    private static final Logger log = LoggerFactory.getLogger(MissingRestAccessDeniedHandler.class);
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        String value = new ObjectMapper().writeValueAsString(ResultData.error("没有权限访问"));
        response.setStatus(403);
        // 设置响应内容类型为JSON
        response.setContentType("application/json");
        // 设置字符编码为UTF-8
        response.setCharacterEncoding("UTF-8");
        // 获取response的writer对象
        PrintWriter out = response.getWriter();
        out.write(value);
        log.error("没有权限访问");
        // 清空缓冲区，发送数据
        out.flush();
        out.close();
    }
}
